#include "common/common.h"
#include "thread_pool.h"


void tq_init(task_queue* tq, int size){
    tq->size = size;
    tq->total = 0;
    tq->head = 0;
    tq->tail = 0;
    pthread_mutex_init(&tq->mutex, NULL);
    pthread_cond_init(&tq->cond, NULL);
    tq->data = (char**)calloc(size, sizeof(char*));
    for(int i = 0; i < size; i++){
        tq->data[i] = (char*)calloc(MAX_LINE, sizeof(char));
    }
    return;
}

void tq_push(task_queue *tq, char* str){
    pthread_mutex_lock(&tq->mutex);
    //判断队列是否已满
    while(tq->size == tq->total){
        DBG(RED"queue is fulled!\n"NONE);
        pthread_mutex_unlock(&tq->mutex);
        usleep(100000);
        pthread_mutex_lock(&tq->mutex);
    }

    strncpy(tq->data[tq->tail], str, MAX_LINE);
    tq->total++;
    if(++tq->tail == tq->size){
        tq->tail = 0;
    }
    DBG(GREEN"push : %s"NONE, tq->data[tq->tail]);
    pthread_cond_signal(&tq->cond);
    pthread_mutex_unlock(&tq->mutex);
    return; 
}

void tq_pop(task_queue *tq, char* str){
    pthread_mutex_lock(&tq->mutex);
    //判空
    while(tq->total == 0){
        DBG(RED"queue is empty!\n"NONE);
        pthread_cond_wait(&tq->cond, &tq->mutex);
    }
    strncpy(str, tq->data[tq->head], MAX_LINE);
    tq->total--;
    if(++tq->head == tq->size){
        tq->head = 0;
    }
    pthread_mutex_unlock(&tq->mutex);
    return;
}


void* do_work(void* args){
    task_queue* tq = (task_queue*) args;
    char* buf = (char*)calloc(MAX_LINE, sizeof(char));
    while(1){
        tq_pop(tq, buf);
        DBG(BLUE"<%ld> : %s"NONE, pthread_self(), buf);  
        //printf("%s", buf); 
    }
    return NULL;
}
